package com.project.class9_1.one.dao.impl;

import com.project.class9_1.one.bean.LogBean;
import com.project.class9_1.one.dao.ILogDao;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DaoProxy implements InvocationHandler {
    private Object targetObj;
    private ILogDao logDao = new LogDaoImpl();
    public DaoProxy(Object targetObj){
        this.targetObj = targetObj;
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(targetObj.getClass().getClassLoader(),
                targetObj.getClass().getInterfaces(),this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //得到目标方法执行前的毫秒数
        long startTime = System.currentTimeMillis();
        //执行目标方法
        Object returnObj = method.invoke(targetObj,args);
        //得到目标方法执行后的毫秒数
        long endTime = System.currentTimeMillis();
        //得到方法运行时间
        long runTime = endTime - startTime;

        //得到日志内容
        String content = "执行"+targetObj.getClass().getName()+"的"+method.getName()+
                "，毫时"+runTime+"毫秒";
        //记录日志
        logDao.add(new LogBean(content));

        return returnObj;
    }
}
